package com.mingqijia.gassafety.webserver.service.cmp;

import com.alibaba.fastjson.JSONObject;
import com.mingqijia.gassafety.shared.constant.Constants;
import com.mingqijia.gassafety.shared.constant.UrlConst;
import com.mingqijia.gassafety.shared.utils.HttpUtil;
import com.mingqijia.gassafety.webserver.response.sk.ConsoleSkSupplierListResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author zhangfei
 * @version 1.0.0
 * @ClassName EquipmentCmpService.java
 * @createTime 2022年08月08日
 */
@Component
@Slf4j
public class EquipmentCmpService {

    @Value(value = "${gassafety.cmp.url}")
    public String targetUrl;
    @Value(value = "${gassafety.cmp.appId}")
    public String appId;

    @Value(value = "${gassafety.cmp.productIdTelecom}")
    public String productIdTelecom;
    @Value(value = "${gassafety.cmp.productIdMove}")
    public String productIdMove;
    @Value(value = "${gassafety.cmp.productIdUnicom}")
    public String productIdUnicom;
    @Value(value = "${gassafety.cmp.productIdWiFi}")
    public String productIdWiFi;
    @Value(value = "${gassafety.cmp.productIdCat}")
    public String productIdCat;

    @Autowired
    HttpUtil httpUtil;

    @Autowired
    RedisTemplate redisTemplate;

    /**
     * cmp请求
     * @param jsonData 请求体
     * @param type  0创建设备 1删除更新设备
     * @param headers
     * @param param
     * @return
     */
    public Map<String, Object> cmpRequest(Map<String, Object> jsonData, int type
            ,Map<String,String> headers,String param) {
        log.info("EquipmentCmpService——cmpRequest,主要发送数据：{},type：{}",
                JSONObject.toJSONString(jsonData), type);
        Map<String, Object> resultMap = new HashMap<>();
        boolean result = true;
        JSONObject jsonObject = null;
        try {
            String url = "";
            if (type == 0) {
                url = targetUrl + UrlConst.CREATE_EQUIPMENT_CMP.getUrl();
            } else if (type == 1) {
                url = targetUrl + UrlConst.UPDATE_REMOVE_EQUIPMENT_CMP.getUrl()+param;
            } else if (type == 2) {
                url = targetUrl + UrlConst.UPDATE_REMOVE_EQUIPMENT_CMP.getUrl()+param;
            } else if (type == 3) {
                url = targetUrl + UrlConst.QUERY_EQUIPMENT_CMP.getUrl();
            }
            log.info("EquipmentCmpService——url：{}", url);
            String jsonStr = JSONObject.toJSONString(jsonData);
            String body = HttpUtil.getBody(jsonStr, url, "", headers,type);
            log.info("EquipmentCmpService——cmpRequest,响应结果body：{}",
                    JSONObject.toJSONString(body));
            jsonObject = JSONObject.parseObject(body);
            if (jsonObject == null) return resultMap;
            if (Integer.parseInt(jsonObject.get("code") + "") != 0) {
                result = false;
                resultMap.put("msg", jsonObject.get("msg"));
            }
            resultMap.put("code",jsonObject.get("code")+"");
            resultMap.put("data",jsonObject.get("data")+"");
        } catch (Exception e) {
            log.error("EquipmentCmpService-error:{}", e);
            throw e;
        }
        resultMap.put("result", result);
        return resultMap;
    }

    /**
     *
     * Description: 根据cmp平台的imei去查询，不是deviceId <br>
     *
     * @author 王伟<br>
     * @taskId <br>
     * @param params
     * @return <br>
     */
    public JSONObject query(Map<String, Object> params, Map<String,String> headers) {
        log.info("EquipmentCmpService——query,主要发送数据：{}",
                JSONObject.toJSONString(params));
        JSONObject resultMap = new JSONObject();
        boolean result = true;
        JSONObject jsonObject = null;
        try {
            String url = targetUrl + UrlConst.QUERY_EQUIPMENT_CMP.getUrl() + "?imei=" + (params.get("imei") == null ? "" : (String)params.get("imei"));
            String s = httpUtil.doGet(url, headers);
            log.info("EquipmentCmpService——query,响应结果body：{}",
                    JSONObject.toJSONString(s));
            if (StringUtils.isEmpty(s)) {
                result=false;
                log.error("EquipmentCmpService——query:{}",s);
                resultMap.put("msg", "查询结果为空");
            }else {
                jsonObject = JSONObject.parseObject(s);
                if (jsonObject.getInteger("code") == 0) {
                    JSONObject data = jsonObject.getJSONObject("data");
                    if(data != null) {
                        resultMap = data;
                    }
                } else {
                    resultMap.put("msg", jsonObject.get("msg"));
                }
            }
        } catch (Exception e) {
            log.error("EquipmentCmpService-error:{}", e);
            result=false;
        }
        resultMap.put("result",result);
        return resultMap;
    }


    public Map<String, String> getHeaders(Integer type) {
        log.info("getHeaders-param:{}",type);
        Map<String, String> headers = new HashMap<>();
        String product = "";
        if (type ==  Constants.MOVE_EQUIPMENT_DEVICETYPE) {
            product=productIdMove;
        } if (type == Constants.TELECOM_EQUIPMENT_DEVICETYPE) {
            product=productIdTelecom;
        } else if (type == Constants.UNICOM_EQUIPMENT_DEVICETYPE) {
            product=productIdUnicom;
        }else if (type == Constants.ZJ_EQUIPMENT_DEVICETYPE){
                product=  productIdWiFi;
        }else if (type == Constants.CAT_EQUIPMENT_DEVICETYPE){
            product=  productIdCat;
        }
        headers.put("APP-Id", appId);
        headers.put("Request-Id", UUID.randomUUID().toString().replaceAll("-", ""));
        headers.put("Product-Id",product);
        log.info("getHeaders-headers:{}",JSONObject.toJSONString(headers));
        return headers;
    }

    /**
     * cmp请求
     * @return
     */
    public ConsoleSkSupplierListResponse supplierListRequest() {
        ConsoleSkSupplierListResponse listResponse = new ConsoleSkSupplierListResponse();
        try {
            String rKey = Constants.EQUIPMENT_MANUFACTURER_REDIS_KEY;
            Object obj = redisTemplate.opsForValue().get(rKey);
            String body = obj==null?"":obj.toString();
            if (StringUtils.isEmpty(body)){
                Map<String, Object> jsonData = new HashMap<>();
                jsonData.put("supplierType", "4");
                log.info("supplierListRequest——主要发送数据：{},type：{}",
                        JSONObject.toJSONString(jsonData));
                String url = targetUrl + UrlConst.QUERY_SUPPLIER_LIST.getUrl();
                log.info("supplierListRequest——url：{}", url);
                String jsonStr = JSONObject.toJSONString(jsonData);
                body = HttpUtil.getSupplierBody(jsonStr, url, "", getSupplierHeaders());
                log.info("supplierListRequest——响应结果body：{}",
                        JSONObject.toJSONString(body));
                listResponse = JSONObject.parseObject(body, ConsoleSkSupplierListResponse.class);
                if (listResponse != null && listResponse.getCode() == 0 &&
                        listResponse.getData() != null && !listResponse.getData().isEmpty() ) {
                    redisTemplate.opsForValue().set(rKey,body,20*60, TimeUnit.SECONDS);
                }
            }else{
                log.info("supplierListRequest——redis缓存中的响应结果body：{}",
                        JSONObject.toJSONString(body));
                listResponse = JSONObject.parseObject(body, ConsoleSkSupplierListResponse.class);
            }
        } catch (Exception e) {
            log.error("supplierListRequest-error:{}", e);
            throw e;
        }
        return listResponse;
    }

    public Map<String, String> getSupplierHeaders() {
        Map<String, String> headers = new HashMap<>();
        headers.put("APP-Id", appId);
        headers.put("Request-Id", UUID.randomUUID().toString().replaceAll("-", ""));
        log.info("getHeaders-headers:{}",JSONObject.toJSONString(headers));
        return headers;
    }
}